<?php

namespace App\Http\Controllers;

use App\Http\Lib\isAdmin;
use App\Models\Users;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use App\Http\Lib\ResBase;
use App\Http\Lib\TokenServise;
use PHPUnit\Exception;
use App\Events\DemoEvent;
use function PHPUnit\Framework\isEmpty;

class UserController extends Controller
{

    //用户注册
    public function register(Request $request){
        $data = $request->all();
        //数据验证
        $validator = validator($data,[
            'username' =>['required'],
            'password' =>['required'],
            'rePassword' => ['required','same:password']
        ],[
            'username.required' => '用户名不能为空!',
            'password.required' => '密码不能为空!',
            'rePassword.required' => '确认密码不能为空!',
            'rePassword.same' => '两次密码输不一致!',
        ]);

        if($validator ->fails()){
            return ResBase::ApiRes(400,$validator->errors(),'fail');
        } else {
            $u = Users::where('user_name',$data['username'])->first();
            if(!empty($u)){
                return ResBase::ApiRes(401,'用户名已存在','failed');
            } else {
                @$user = new Users();
                $user -> user_name = $data['username'];
                $user -> password = md5($data['password']);
                $user -> user_id = substr(session_create_id(),0,5);
                $user ->save();
                return ResBase::ApiRes(200,['id'=>$user -> user_id,'username' =>$user -> user_name ],'注册成功!');
            }
        }
    }

    public function login(Request $request){
        $data = $request->all();
        $password = md5($data['password']);
        $validator = validator($data,[
            'username' => 'required',
            'password' => 'required',
        ],[
            'username.required' => '用户名不能为空!',
            'password.required' => '密码不能为空!'
        ]);
        if($validator->fails()){
            return ResBase::ApiRes(401,$validator->errors(),'failed');
        } else {
            $u = Users::where('user_name',$data['username']) ->where('password',$password) ->first();
            $token = TokenServise::createToken($u['user_id']);
            if (!empty($u)){
                return ResBase::ApiRes(200,['id' => $u['user_id'],'username'=>$u['user_name'],'token'=>$token, 'root'=>$u['root']],'success');
            } else {
                return ResBase::ApiRes(400,'用户名或密码错误','failed');
            }
        }
    }

    public function edit(Request $request){
        $data = $request->all();
        $name = $data['newusername'];
        $id = $data['userId'];
        $tel = $data['tel'] ?? null;
        $address = $data['address'] ?? null;
        $validator = validator($data,[
            'newusername'=>'required',
            'userId'=>'required',
        ],[
            'newusername.required'=>'用户名不能为空',
            'userId.required'=>'用户名不能为空',
        ]);

        if($validator->fails()){
            return ResBase::ApiRes(402,'数据验证失败','failed');
        } else {
            $u = Users::where('user_name', $name)->first();
            if($u){
                return ResBase::ApiRes(400,'用户名已存在','failed');
            }
            $r = Users::where('user_id', $id)->first();
            if($r['user_name'] === $name){
                return ResBase::ApiRes(401,'用户名不能和修改前一致','failed');
            }
            try {
                $res = Users::where('user_id',$id)->update([
                    'user_name'=> $name,
                    'tel'=> $tel?$tel:'',
                    'address'=> $address?$address:'',
                ]);
                if(!$res){
                    return ResBase::ApiRes(405,'修改失败','failed');
                } else {
                    return ResBase::ApiRes(200,'修改成功!');
                }
            } catch (Exception $e) {
                return ResBase::ApiRes(403,$validator->errors(),'failed');
            }
        }
    }

    public function password(Request $request){
        $data = $request->all();
        $validator = validator($data,[
            'password' => 'required',
            'repassword' => ['required','same:password'],
        ],[
            'password.required' => '密码不能忘为空',
            'repassword.required' => '确认密码不能忘为空',
            'repassword.same' => '两次密码输入不一致',
        ]);

        if($validator->fails()){
            return ResBase::ApiRes(401,'密码格式错误','failed');
        } else {
            try {
                $res = Users::where('user_id',$data['id'])->update(['password'=> md5($data['password'])]);
                if(!$res) {
                    return ResBase::ApiRes(400,'修改失败','fail');
                }
                return ResBase::ApiRes(200,['id' => $data['id']],'success');
            } catch (\Exception $e){
                return ResBase::ApiRes(400,$e->getMessage(),'fail');
            }
        }
    }

    //获取用户信息
    public function getuserinfo(Request $request){
        $id = $request->input('userId');
        $res = Users::find($id);
        $i=[
            'username'=>$res['user_name'],
            'userid'=>$res['user_id'],
            'tel'=>$res['tel'],
            'address'=>$res['address'],
            'isAdmin'=>$res['isAdmin'],
            'userRetime'=> $res['created_at'],
        ];
        if($res){
            return ResBase::ApiRes(200,$i,'success');
        } else {
            return ResBase::ApiRes(400,'获取信息失败','failed');
        }
    }

    //phpinfo
    public function getphpinfo(){
        phpinfo();
    }

    public function redis(){
        broadcast(new \App\Events\DemoEvent("123321"));
    }

    //拉取用户列表
    public function getUsers(Request $request){
//        $res = Users::where('deleted_at','null')->get();
        $res = Users::orderBy('created_at','desc')->get();
//        var_dump($res);
        $list = [];
        foreach ($res as $i){
            array_push($list,['name'=>$i->user_name,'root'=>$i->root,'id'=>$i->user_id]);
        }
        return ResBase::ApiRes(200,$list);
    }

    //拉取注册用户申请列表
    public function getNewUsers(Request $request){
        $res = Users::where('status',0)->get();
        $list = [];
        foreach ($res as $i){
            array_push($list,['name'=>$i->user_name,'root'=>$i->root,'id'=>$i->user_id]);
        }
        return ResBase::ApiRes(200,$list);
    }

    //新用户审批
    public function newUser(Request $request){
        $newUserId = $request->input('newUserId');
        $id = $request->input('userId');
        $userres = isAdmin::isadmin($id);
        if($userres){
            return $userres;
        }
        $suggest = $request->input('suggest');
        $user = Users::where('user_id',$newUserId)->first();
        if(!$user){
            return ResBase::ApiRes(404,'未查询到该用户','failed');
        } else {
            $user->status = $suggest;
            $res = $user->save();
            if(!$res){
                return ResBase::ApiRes(400,'审批失败','failed');
            } else {
                return ResBase::ApiRes(200,'审批成功','failed');
            }
        }
    }

}
